<template>
  <div class="execution">
    <basic-container>
      <avue-crud ref="crud" :page.sync="page" :data="tableData" :permission="permissionList" :table-loading="tableLoading" :option="tableOption" @on-load="getList" @search-change="searchChange" @refresh-change="refreshChange" @size-change="sizeChange" @current-change="currentChange" @row-update="handleUpdate" @row-save="handleSave" @row-del="handleDel">
        <template slot="menuLeft">
          <el-button class="filter-item" v-if="permissions.product_sputag_del" plain type="danger" size="small" icon="el-icon-remove" @click="handleDels">批量删除</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button v-if="permissions.product_attr_add" type="text" size="small" icon="el-icon-menu" @click="handleSpuTagReference(scope.row,scope.index)">关联商品</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog :visible.sync="dialogSpuTagReferenceVisible" width="30%" :close-on-click-modal="false" append-to-body title="关联商品">
      <div class="dialog-main-select">
        <el-select v-model="dialogSpuTagReferenceIds" multiple filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="dialogSpuTagReferenceList" :loading="dialogSpuTagReferenceLoading">
          <el-option v-for="item in dialogSpuTagReferenceOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="updateDialogSpuTagReference(tagId)" :disabled="listLoading">更 新</el-button>
        <el-button type="default" size="small" @click="cancalDialogSpuTagReference()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, referenceSpu, getObj, addObj, putObj, putSpuTagReferenceObj, delObj, delObjs } from '@/api/product/spuTag'
import { tableOption } from '@/const/crud/product/spuTag'
import * as spuApi from '@/api/product/spu'
import { mapGetters } from 'vuex'

export default {
  name: 'sputag',
  data() {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,

      //======属性值表格相关=====
      tagId: undefined,
      dialogSpuTagReferenceVisible: false,
      dialogSpuTagReferenceIds: [],// 已关联商品
      dialogSpuTagReferenceOptions: [],// 下拉商品
      dialogSpuTagReferenceLoading: false,
      listLoading: false,
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permissions.product_sputag_view, false),
        addBtn: this.vaildData(this.permissions.product_sputag_add, false),
        delBtn: this.vaildData(this.permissions.product_sputag_del, false),
        editBtn: this.vaildData(this.permissions.product_sputag_edit, false)
      };
    }
  },
  methods: {
    // 列表查询
    getList(page, params) {
      this.tableLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 删除
    handleDel: function(row, index) {
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    // 批量删除
    handleDels: function(row, index) {
      if (this.$refs.crud.tableSelect.length === 0) {
        this.$message.error('请选择后进行删除')
        return false
      }
      let Ids = []
      for (const row of this.$refs.crud.tableSelect) {
        Ids.push(row.row.id)
      }
      delObjs(Ids).then(() => {
        this.$notify.success('删除成功')
        this.$refs.crud.toggleSelection();
        this.refreshChange();
      })
    },
    // 更新
    handleUpdate: function(row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    // 保存
    handleSave: function(row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page)
    },

    //======规格表格相关=====
    handleSpuTagReference: function(row) {
      referenceSpu({ tagId: row.id }).then(res => {
        this.dialogSpuTagReferenceIds = []
        this.dialogSpuTagReferenceOptions = []

        let referenceSpus = res.data.data;
        referenceSpus.forEach(x => {
          if (x.tagId) {
            this.dialogSpuTagReferenceIds.push(x.spuId)
          }
          this.dialogSpuTagReferenceOptions.push({
            value: x.spuId,
            label: x.name,
          })
        });
        this.tagId = row.id
        this.dialogSpuTagReferenceVisible = true
      })
    },
    dialogSpuTagReferenceList: function(query) {
      if (query !== '') {
        this.dialogSpuTagReferenceLoading = true;
        setTimeout(() => {
          this.dialogSpuTagReferenceLoading = false;
          spuApi.fetchList({ current: 1, size: 20, name: query }).then(res => {
            this.dialogSpuTagReferenceOptions = res.data.data.records.map(x => {
              return {
                value: x.spuId,
                label: x.name,
              }
            })
          })
        }, 200)
      }
    },
    updateDialogSpuTagReference() {
      this.listLoading = true;
      setTimeout(() => {
        this.listLoading = false;
        putSpuTagReferenceObj({
          spuIds: this.dialogSpuTagReferenceIds,
          tagId: this.tagId,
        }).then(res => {
          this.dialogSpuTagReferenceVisible = false;
        });
      }, 200)
    },
    cancalDialogSpuTagReference() {
      this.dialogSpuTagReferenceVisible = false;
    },
  }
}
</script>